package com.jianyun.jyzs.receive;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by AMing on 17/6/16.
 * Company RongCloud
 * 网络接收
 */
public class NetworkConnectChangedReceiver extends BroadcastReceiver {

    public static final String CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (activeNetwork != null) {
                if (activeNetwork.isConnected() && networkChangeStatusListener != null) {
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        networkChangeStatusListener.onChange(true);
                    }
                } else if (networkChangeStatusListener != null) {
                    networkChangeStatusListener.onChange(false);
                }
            } else if (networkChangeStatusListener != null) {
                networkChangeStatusListener.onChange(false);
            }
        }

    }

    public interface NetworkChangeStatusListener {
        void onChange(boolean isHasNetwork);
    }

    private NetworkChangeStatusListener networkChangeStatusListener;

    public void setNetworkChangeStatusListener(NetworkChangeStatusListener networkChangeStatusListener) {
        this.networkChangeStatusListener = networkChangeStatusListener;
    }
}
